<span class="length-indicator {overLimit ? 'over-char-limit' : ''}"
      aria-live={lengthVerbosity}
      aria-atomic='true'
      {style}
>{lengthToDisplayDeferred}</span>
<style>
  .length-indicator {
    color: var(--length-indicator-color);
    font-size: 1.3em;
  }

  .length-indicator.over-char-limit {
    color: var(--warning-color);
  }
</style>
<script>
  import { mark, stop } from '../_utils/marks.js'
  import { store } from '../_store/store.js'
  import { observe } from 'svelte-extras'
  import { throttleTimer } from '../_utils/throttleTimer.js'
  const updateDisplayedLength = process.browser && throttleTimer(requestAnimationFrame)

  // How many chars within the limit to start warning at
  const WARN_THRESHOLD = 10

  export default {
    oncreate () {
      const { lengthToDisplay } = this.get()
      this.set({ lengthToDisplayDeferred: lengthToDisplay })
      // perf improvement for keyboard input latency
      this.observe('lengthToDisplay', () => {
        updateDisplayedLength(() => {
          mark('set lengthToDisplayDeferred')
          const { lengthToDisplay } = this.get()
          this.set({ lengthToDisplayDeferred: lengthToDisplay })
          stop('set lengthToDisplayDeferred')
        })
      }, { init: false })
    },
    data: () => ({
      lengthToDisplayDeferred: 0,
      style: ''
    }),
    store: () => store,
    computed: {
      lengthToDisplay: ({ length, max }) => max - length,
      lengthVerbosity: ({ lengthToDisplayDeferred }) => {
        // When approaching the limit, notify screen reader users
        if (lengthToDisplayDeferred > WARN_THRESHOLD) {
          return 'off'
        } else {
          return 'polite'
        }
      }
    },
    methods: {
      observe
    }
  }
</script>
